import type { ForwardedRef, ReactNode } from 'react'
import React, {
  forwardRef,
  memo,
  useImperativeHandle,
  useRef,
  useState
} from 'react'
import { FormInstance } from 'antd'
import BaseModal, { IBaseModalRef } from '@/base-ui/base-modal'
import { IModalConfig } from '@/components/page-modal/type'

interface IProps {
  children?: ReactNode
  // 外面可以通过这个属性拿到from实例
  onOk: (form: FormInstance | undefined) => void
  onCancel: (form: FormInstance | undefined) => void
  // ---
  modalConfig: IModalConfig
}

export interface IModalComponentRef {
  openModal: () => void
  closeModal: () => void
  getFormInstance: () => FormInstance<any> | undefined
  updateFormView: (values: any) => void
}

const PageModal = (props: IProps, ref: ForwardedRef<any>) => {
  const { modalConfig, onOk, onCancel } = props
  const [isShowModal, setIsShowModal] = useState(false)
  const baseModalRef = useRef<IBaseModalRef>()

  // 子组件向外暴露打开和关闭弹框的方法
  useImperativeHandle(ref, () => ({
    openModal() {
      setIsShowModal(true)
    },
    closeModal() {
      setIsShowModal(false)
    },
    getFormInstance() {
      return baseModalRef.current?.getFormInstance()
    },
    updateFormView(values: any) {
      baseModalRef.current?.updateFormView(values)
    }
  }))

  function handleOnConfirm(form: FormInstance | undefined) {
    onOk(form)
  }

  function handleOnCancel(form: FormInstance | undefined) {
    onCancel(form)
  }

  return (
    <BaseModal
      ref={baseModalRef}
      modalConfig={modalConfig}
      open={isShowModal}
      onConfirm={handleOnConfirm}
      onCancel={handleOnCancel}
    >
      {props.children}
    </BaseModal>
  )
}

export default memo(forwardRef(PageModal))
